package evi.com.evi.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import evi.com.evi.R;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 修改商品类别，添加商品类别
 *
 * @author MY
 */
public class GoodsUpdateActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "TAG";
    private ImageView tv_return_back; // 返回
    private TextView tv_save;
    private EditText et_input;

    private String ActType = "";
    private TextView tv_title;

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_goods_update);

        ActType = getIntent().getStringExtra("ActType");

        initView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_return_back: // 返回
                this.finish();
                break;
            case R.id.tv_save: // 保存
                if ("添加分类".equals(ActType)) {
                    addSort();
                } else if ("修改分类".equals(ActType)) {
                    updateSort();
                }
                break;
            default:
                break;
        }
    }

    private void initView() {
        tv_return_back = (ImageView) findViewById(R.id.tv_return_back);
        tv_return_back.setOnClickListener(this);

        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_save.setOnClickListener(this);

        et_input = (EditText) findViewById(R.id.et_input_username);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(ActType);
        if ("添加分类".equals(ActType)) {
            et_input.setHint("请输入分类名称（8字以内）");
        } else if ("修改分类".equals(ActType)) {
            String name = getIntent().getStringExtra("name");
            et_input.setHint(name);
        }

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();
    }


    /**
     * 添加分类
     */
    private void addSort() {
        String name = et_input.getText().toString();

        if (et_input.getText().toString().length() > 8) {
            name = et_input.getText().toString().substring(0, 8);
        }

        String token = SPUtil.getString(this, "token");

        FormBody.Builder builder = new FormBody.Builder();

        RequestBody body = builder.add("name", name).build();

        Request request = new Request.Builder()
                .addHeader("token", token)
                .post(body)
                .url(ContentUtils.addProductCategory_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                Log.e(TAG, "接口访问结果：" + jsonData);
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showMsg(GoodsUpdateActivity.this, "添加分类成功");
                                setResult(RESULT_OK);
                                finish();
                            }
                        });
                    } else {
                        toast("添加分类失败");
                    }
                }
                Log.e(TAG, "添加商品分类联网成功" + jsonData);
            }
        });

    }

    /**
     * 修改分类
     */
    private void updateSort() {
        String name = et_input.getText().toString();
        String productCategoryId = getIntent().getStringExtra("productCategoryId");

        String token = SPUtil.getString(this, "token");

        FormBody.Builder builder = new FormBody.Builder();

        RequestBody body = builder
                .add("name", name)
                .add("productCategoryId", productCategoryId)
                .build();

        Request request = new Request.Builder()
                .addHeader("token", token)
                .post(body)
                .url(ContentUtils.updateProductCategory_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                Log.e(TAG, "接口访问结果：" + jsonData);
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showMsg(GoodsUpdateActivity.this, "修改分类成功");
                                setResult(RESULT_OK);
                                finish();
                            }
                        });
                    } else {
                        toast("修改分类失败");
                    }
                }
                Log.e(TAG, "添加商品分类联网成功" + jsonData);
            }
        });

    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(GoodsUpdateActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }

}
